/**   
 * @Title: LotteryRecrodTotalAct.java 
 * @Package com.esun.cheetah.view.personal.lotteryrecord.LotteryRecordTotalAct
 * @Description: (显示全部购彩记录Activity) 
 * @author 孔祥攀 <br/>
 * @date 2012-4-13 下午2:44:19 
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.cheetah.view.personal.lotteryrecord;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.personal.lotteryrecord.GetLotteryRecordListCommunicater;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.model.personal.LotteryRecordsBean;
import com.esun.cheetah.network.ConnectionChangeReceiver;
import com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListView;
import com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListView.OnPrepareForRefreshListener;
import com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListView.OnRefreshListener;
import com.esun.util.log.EDebug;

/**
 * 
 * @Package com.esun.cheetah.view.personal.lotteryrecord.LotteryRecordTotalAct
 * @ClassName: LotteryRecordTotalAct
 * @Description: TODO(显示全部购彩记录)
 * @author 孔祥攀 <br/>
 * @date 2012-4-13 下午2:44:19
 * 
 */
public class LotteryRecordTotalAct extends Activity implements
		OnScrollListener, OnItemClickListener, OnRefreshListener,
		OnPrepareForRefreshListener {
	private PullToRefreshListView listViewLotteryRecordTotal; // 全部购彩记录列表
	private ArrayList<Hashtable<String, String>> alItem; // 列表数据存储
	private ArrayList<View> itemViewList;
	private LotteryRecordListAdapterModify adapter;
	private LinearLayout linearFooter; // 列表底部加载布局
	// private LinearLayout linearNoMore;
	private LinearLayout linearBottom;
	private ProgressDialog progressDialog;
	public static Handler handlerGetTotalLotteryRecord;
	private GetLotteryRecordListCommunicater totalLotteryRecordCommunicater;
//	private String serverMessage; // 服务器返回信息
	private int refreshORBottom = 2; // state=1刷新 state=2到底部

	private Intent intent;
	private Bundle bundle;
	private LinearLayout linearNoMoreRecord;
	private boolean isShow = true;
	private boolean isRunning;// 是否正在通信
	private boolean isFirstLoad = true; // 是否是第一次加载
	private boolean isNoMoreRecord = true; // 是否还有记录
	private boolean isBottomChanged = false;

	private final String LOTID = "46"; // 通信所需参数 , 0全部; 46竞彩足球
	private final String SELTYPE = "-1";// 通信所需参数 , 0未结; 1已结; -1全部
	private final String TIME = "-99";// 0全部，-7最近一周，N天数

	private int PAGENO = 1;

	private final int FOOTER_VIEW_TAG = 10000;
	private final int FOOTER_VIEW_TAG2 = 20000;
	private final int FOOTER_VIEW_TAG3 = 30000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lotteryrecord_total_act);

		initUI();
		initHandler();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isShow = false;
		this.unregisterReceiver(ConnectionChangeReceiver
				.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isShow = true;
		this.registerReceiver(
				ConnectionChangeReceiver.getConnectionChangeReceiver(),
				ConnectionChangeReceiver.getIntentFilter());
		if (UserInfo.getUserInfo().isRebuy()) {
			getParent().finish();
		}
	}

	// 初始化
	public void initUI() {

		isRunning = false;

		// progressDialog =
		// ViewerUtil.showProgressDialog(LotteryRecordTotalAct.this,
		// getResources().getString(R.string.loading_text));
		// progressDialog.show();

		listViewLotteryRecordTotal = (PullToRefreshListView) findViewById(R.id.lotteryrecordtotalact_listview);
		linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.lotteryinfoact_linear_footer, null);
		// linearNoMore = (LinearLayout)
		// LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore,
		// null);
		linearBottom = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.listview_bottom_view, null);
		linearFooter.setTag(FOOTER_VIEW_TAG);
		// linearNoMore.setTag(FOOTER_VIEW_TAG2);
		linearBottom.setTag(FOOTER_VIEW_TAG3);

		alItem = new ArrayList<Hashtable<String, String>>();
		itemViewList = new ArrayList<View>();
		adapter = new LotteryRecordListAdapterModify(
				LotteryRecordTotalAct.this, alItem, itemViewList);
		listViewLotteryRecordTotal.addFooterView(linearFooter);// 增加底部状态条
		listViewLotteryRecordTotal.setAdapter(adapter);
		listViewLotteryRecordTotal.removeFooterView(linearFooter);
		linearNoMoreRecord = (LinearLayout) findViewById(R.id.lotteryrecord_totalact_linear_noRecord);

		listViewLotteryRecordTotal.setOnItemClickListener(this);
		listViewLotteryRecordTotal.setOnRefreshListener(this);
		listViewLotteryRecordTotal.setOnScrollListener(this);
		listViewLotteryRecordTotal.setOnPrepareForRefreshListener(this);

	}

	// 与服务器通信线程
	public void getTotalLotteryRecordThread() {
		totalLotteryRecordCommunicater = new GetLotteryRecordListCommunicater(
				handlerGetTotalLotteryRecord, LOTID, SELTYPE, PAGENO, TIME);
		totalLotteryRecordCommunicater.startCommunicate();
	}

	// 消息处理
	public void initHandler() {
		handlerGetTotalLotteryRecord = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				listViewLotteryRecordTotal.removeFooterView(linearBottom);

				switch (msg.what) {

				case Config.COMMUNICATER_SUCCESS:

					PAGENO++;
					communicateSucceed(totalLotteryRecordCommunicater
							.getLotteryRecordsList());
					itemViewList.clear();
					adapter.notifyDataSetChanged();
					if (totalLotteryRecordCommunicater.getLotteryRecordsList()
							.size() < 10) {
						isNoMoreRecord = false;
						// listViewLotteryRecordTotal.addFooterView(linearNoMore);
					}
					lengthAutoAdapter();
					endProcess();
					break;

				case Config.COMMUNICATER_FAIL:

					if (isShow) {
						// ViewerUtil.showTipDialog(LotteryRecordTotalAct.this,
						// totalLotteryRecordCommunicater.getServerMsg(),
						// false);
						Toast.makeText(
								LotteryRecordTotalAct.this,
								totalLotteryRecordCommunicater.getServerMsg()
										.toString(), 0).show();
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case Config.COMMUNICATER_EXCEPTION:

					if (isShow) {
//						linearNoMoreRecord.setVisibility(View.VISIBLE);
//             listViewLotteryRecordTotal.setVisibility(View.GONE);
             
            // ViewerUtil.showTipDialog(LotteryRecordTotalAct.this, Language.STR_CONNECTIONFAIL, false);
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case Config.DO_REFRESH:
					EDebug.o(this, "do refresh");
					if (!isRunning) {
						listViewLotteryRecordTotal.prepareForRefresh();
						listViewLotteryRecordTotal.onRefresh();
						// progressDialog.show();
					}
					LotteryRecordAgp.isCanClick = true;

					break;

				default:
					break;
				}
			}
		};
	}

	private void endProcess() {
		if (refreshORBottom == 1) {
			listViewLotteryRecordTotal.onRefreshComplete();
		} else {
			listViewLotteryRecordTotal.removeFooterView(linearFooter);
		}
		if (progressDialog != null) {
			progressDialog.cancel();
		}
		isRunning = false;
	}

	// 通讯成功处理
	public void communicateSucceed(
			ArrayList<LotteryRecordsBean> LotteryRecordsList) {

		ArrayList<Hashtable<String, String>> alItemTemp = new ArrayList<Hashtable<String, String>>();

		for (int i = 0; i < LotteryRecordsList.size(); i++) {

			Hashtable<String, String> map = new Hashtable<String, String>();
			map.put("istitle", "no");
			// 显示参数
			map.put("addtime", LotteryRecordsList.get(i).addtime);
			map.put("expect", LotteryRecordsList.get(i).expect);
			map.put("paymoney", LotteryRecordsList.get(i).paymoney);
			map.put("playname", LotteryRecordsList.get(i).playname);
			map.put("getmoney", LotteryRecordsList.get(i).getmoney);
			map.put("isjprize", LotteryRecordsList.get(i).isjprize);
			map.put("isprize", LotteryRecordsList.get(i).isprize);
			map.put("issuc", LotteryRecordsList.get(i).issuc);
			map.put("lotname", LotteryRecordsList.get(i).lotname);
			// 取详情传递参数
			map.put("lotid", "46");
			map.put("uid", LotteryRecordsList.get(i).uid);
			map.put("proid", LotteryRecordsList.get(i).proid);
			map.put("id", LotteryRecordsList.get(i).id);
			map.put("playid", LotteryRecordsList.get(i).playid);
			map.put("faqiren", LotteryRecordsList.get(i).fausername);

			alItemTemp.add(map);
			childCount++;
		}
		if (refreshORBottom == 1) {
			alItem.clear();
		}
		alItem.addAll(alItemTemp);
	}

	// 到底事件
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if ((firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0)) {
			if (isNoMoreRecord) {
				if (isFirstLoad) {
					listViewLotteryRecordTotal.prepareForRefresh();
					listViewLotteryRecordTotal.onRefresh();
					isFirstLoad = false;
				} else {
					if (!isRunning && isBottomChanged) {
						isRunning = true;
						isBottomChanged = false;
						listViewLotteryRecordTotal.addFooterView(linearFooter);
						refreshORBottom = 2;
						getTotalLotteryRecordThread();
					}
				}
			}
		} else {
			isBottomChanged = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	// 判断是否是胆拖，因暂不支持不显示详情
	public static boolean isDanTuo(String str) {
		int[] dantuo = { 123, 135, 137, 141, 142, 143, 172, 175, 176, 177, 178,
				179, 261, 264, 265, 266, 267, 268, 278, 279, 280 };
		boolean b = false;
		for (int i = 0; i < dantuo.length; i++) {
			if (str.equals(String.valueOf(dantuo[i]))) {
				b = true;
				break;
			}
		}
		return b;
	}

	/**
	 * ,123,135,137,141,142,143,172,175,176,177,178,179,261,264,265,266,267,268,
	 * 278,279,280,
	 */

	// 将menu键点击事件返回给父activity处理
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		if (!isRunning) {
			PAGENO = 1;
			isRunning = true;
			isNoMoreRecord = true;
			refreshORBottom = 1;
			groupCount = 0;
			childCount = 0;
			itemViewList.clear();
			linearNoMoreRecord.setVisibility(View.GONE);
			listViewLotteryRecordTotal.setVisibility(View.VISIBLE);
			if (listViewLotteryRecordTotal.getFooterViewsCount() != 0) {
				// listViewLotteryRecordTotal.removeFooterView(linearNoMore);
			}
			getTotalLotteryRecordThread();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		adapter.notifyDataSetChanged();
		// TODO Auto-generated method stub
		if (arg1.getTag() != null
				&& (Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG
						|| Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG2 || Integer
						.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG3)) {
			return;
		} else {
			if (alItem.get(arg2 - 1).get("istitle").equals("no")) {
				if (arg2 <= alItem.size()) {
					Hashtable<String, String> strItem = alItem.get(arg2 - 1);
					String tempStrPlayId = strItem.get("playid");
					if (isDanTuo(tempStrPlayId)) {
						Toast.makeText(LotteryRecordTotalAct.this, "暂不支持胆拖",
								Toast.LENGTH_SHORT).show();
					} else {
						intent = new Intent();
						bundle = new Bundle();
						bundle.putString("lotid", strItem.get("lotid"));
						bundle.putString("id", strItem.get("id"));
						bundle.putString("uid", strItem.get("uid"));
						bundle.putString("proid", strItem.get("proid"));
						bundle.putString("expect", strItem.get("expect"));
						bundle.putString("faqiren", strItem.get("faqiren"));
						bundle.putString("getmoney", strItem.get("getmoney"));
						bundle.putString("playid", tempStrPlayId);
						bundle.putString("lotname", strItem.get("lotname"));
						intent.putExtras(bundle);
						Log.d("log", strItem.get("lotid"));
						if (strItem.get("lotid").equals(Config.JINGCAIZUQIU)) {
							intent.setClass(LotteryRecordTotalAct.this,
									LotteryRecordDetailFootballAct.class);
						}

						startActivity(intent);
					}
				} else {
					Toast.makeText(LotteryRecordTotalAct.this, "暂不支持此彩种",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private int groupCount = 0;
	private int childCount = 0;

	private void lengthAutoAdapter() {
		int itemHeight = 30 * groupCount + childCount * (90 + 1);

		// 判断是否需要加入额外item
		if (itemHeight < listViewLotteryRecordTotal.getHeight()) {
			LinearLayout linearChild = new LinearLayout(this);
			int bheight = 0;
			linearChild.setBackgroundColor(Color.WHITE);
			if (listViewLotteryRecordTotal.getFooterViewsCount() > 0) {
				bheight = listViewLotteryRecordTotal.getHeight() - itemHeight
						- 30;
			} else {
				bheight = listViewLotteryRecordTotal.getHeight() - itemHeight;
			}
			linearBottom.addView(linearChild);
			for (int i = 0; i < linearBottom.getChildCount(); i++) {
				linearBottom.getChildAt(i).getLayoutParams().height = bheight;
				linearBottom.getChildAt(i).getLayoutParams().width = LayoutParams.FILL_PARENT;
			}
			TextView a = new TextView(linearChild.getContext());
			a.setFocusable(true);
			a.setBackgroundResource(R.drawable.anull_icon);
			linearChild.addView(a);
			linearChild.setBackgroundResource(R.drawable.anull_icon);
			linearChild.setVisibility(View.VISIBLE);
			listViewLotteryRecordTotal.addFooterView(linearBottom);
		}
	}

	@Override
	public void onClick(View v) {
	}

	@Override
	public void onPrepareForRefresh() {
	}
}
